//
// Created by sgyt on 2020/3/11.
// pipe管道


#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

int main(int argc,char *argv[])
{
    int fd[2];
    //1.创建管道
    int res = pipe(fd);
    if(res < 0)
    {
        perror("pipe error\n");
    }

    //2.创建子进程
    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork error\n");
    }else if(pid > 0)
    {
        //父进程关闭读
        close(fd[0]);
        //父进程往pipe中写入数据
        sleep(5);
        write(fd[1],"sgyt is good man", strlen("sgyt is good man"));

    }else{
        //确保父进程的写端已经开通
        sleep(1);
        //子进程关闭写
        close(fd[1]);
        char buf[1024];
        memset(buf,0x00, sizeof(buf));
        read(fd[0],buf, sizeof(buf));
        printf("pipe read is [%s]\n",buf);
    }
    return 0;
}
